/**
 * 
 */
package it.uniroma3.dia.digraph.algorithm.utility;

import java.awt.geom.Point2D;
import java.util.Comparator;

import org.graphdrawing.graphml.xmlns.NodeType;

/**
 * @author Cionzo
 *
 */
public class AngleManager implements Comparator<NodeType>{
	
	private NodeType origin;

	public static double getAngle(NodeType origin, NodeType node) {
//		double theta, x, y;
//		x = node.getX()- origin.getX();
//		y = node.getY() - origin.getY();
//		  if (x == 0.0)
//		    return ((y > 0.0) ? 90 : 270);
//		  theta = Math.atan(y/x);
//		  theta *= 360/(2*Math.PI);
//		  if (x > 0.0)
//		    return ((y >= 0.0) ? theta : 360 + theta);
//		  else
//		    return (180+theta);
		return getAngle(origin.getX(), origin.getY(), node.getX(), node.getY());
	}
	
	public static double getAngle(double ox, double oy, double px, double py){
		double theta, x, y;
		x = px - ox;
		y = py - oy;
		  if (x == 0.0)
		    return ((y > 0.0) ? 90 : 270);
		  theta = Math.atan(y/x);
		  theta *= 360/(2*Math.PI);
		  if (x > 0.0)
		    return ((y >= 0.0) ? theta : 360 + theta);
		  else
		    return (180+theta);
	}

	@Override
	public int compare(NodeType o1, NodeType o2) {
		double pc1, pc2;
		pc1 = getAngle(this.origin, o1);
		pc2 = getAngle(this.origin, o2);
		int result = 0;
		
		if (pc1>pc2)
			result = 1;
		else if (pc1<pc2)
			result = -1;	
		
		return result;
	}
	
	
	/**
	 * Set the point to be considered as the origin
	 * @param node
	 */
	public void setOrigin(NodeType node){
		this.origin = node;
	}

	/**
	 * Converts polar to Cartesian coordinates
	 * @param origin the point to be considered as the origin
	 * @param alphaDegrees the angle, expressed in degrees
	 * @param radius the radius
	 * @return an array with the Cartesian coordinates: [xCoord, yCoord]
	 */
	public static double[] convertToCartesianCoords(Point2D origin,
			double alphaDegrees, double radius) {
		double radians = Math.toRadians(alphaDegrees);
		return new double[] {radius * Math.cos(radians) + origin.getX(), radius * Math.sin(radians) + origin.getY()};
	}
	
	
	public static double getSignedAngleDifference(Point2D origin, NodeType a, NodeType b){
		NodeType o = new NodeType();
		o.setX(origin.getX()); o.setY(origin.getY());
		return getAngle(o, a)- getAngle(o, b);
	}
	
	public static double getUnsignedAngleDifference(Point2D origin, NodeType a, NodeType b){
		return Math.abs(getSignedAngleDifference(origin, a, b));
	}
	
	

}
